<script setup>
import { computed } from 'vue'
const { proxy } = getCurrentInstance()

const props = defineProps({
  // 列表主键id
  keyId: {
    type: String,
    default: 'id'
  },
  // 数据
  data: {
    type: Array,
    default: () => []
  },
  //   每一行
  column: {
    type: Array,
    default: () => []
  },
  //   加载状态
  loading: {
    type: Boolean,
    default: false
  },
  //   分页总量
  total: {
    type: String || Number,
    default: 0
  },

  /**
   * 查询分页信息
   * @param {pageNum pageSize} query
   */
  query: {
    type: Object,
    default: {
      pageNum: 1,
      pageSize: 10
    }
  },
  //   高度
  height: {
    type: String,
    default: null
  },
  //   值为空是 显示
  empty: {
    type: String,
    default: ''
  },
  //   是否需要序号
  index: {
    type: Boolean,
    default: true
  },
  //   是否需要复选
  isSel: {
    type: Boolean,
    default: true
  },
  // 是否需要分页
  isPage: {
    type: Boolean,
    default: true
  },
  // 数据总量
  total: {
    required: true,
    type: Number
  },
  // 页数
  page: {
    type: Number,
    default: 1
  },
  // 每页数量
  limit: {
    type: Number,
    default: 20
  },
  pageSizes: {
    type: Array,
    default() {
      return [10, 20, 30, 50]
    }
  },
  // 移动端页码按钮的数量端默认值5
  pagerCount: {
    type: Number,
    default: document.body.clientWidth < 992 ? 5 : 7
  },
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  },
  background: {
    type: Boolean,
    default: true
  },
  autoScroll: {
    type: Boolean,
    default: true
  },
  hidden: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['change'])

// 勾选
const handleSelectionChange = selection => {
  emit('change', { ids: selection.map(item => item[props.keyId]), row: selection })
}

// 筛选 是否有重复 prop
const tableColumn = computed(() => {
  const newData = Array.from(new Set(props.column.map(t => t.prop)))
  if (props.column.length > newData.length) {
    console.error(new Error('p-table组件:传入prop重复,请查看!'))
    proxy.errorMsg('p-table组件:传入prop重复,请查看!')
    return []
  } else {
    return props.column
  }
})

// 做一些东西
const getData = (val, key, label) => {
  if (val && key && val[key]) {
    return val[key]
  } else if (!key) {
    return `${label}的 "prop" 为空`
  } else if (props.empty) {
    return props.empty
  } else {
    return `${label}为空, ${key} -> ${val[key]}`
  }
}

const list = computed(() => {
  if (!Array.isArray(props.data)) {
    proxy.errorMsg('p-table组件:传入prop重复,请查看!')
    return []
  } else {
    return props.data || []
  }
})

const currentPage = computed({
  get() {
    return props.page
  },
  set(val) {
    emit('update:page', val)
  }
})

const pageSize = computed({
  get() {
    return props.limit
  },
  set(val) {
    emit('update:limit', val)
  }
})
function handleSizeChange(val) {
  if (currentPage.value * val > props.total) {
    currentPage.value = 1
  }
  emit('pagination', { page: currentPage.value, limit: val })
  if (props.autoScroll) {
    scrollTo(0, 800)
  }
}
function handleCurrentChange(val) {
  emit('pagination', { page: val, limit: pageSize.value })
  if (props.autoScroll) {
    scrollTo(0, 800)
  }
}
</script>

<template>
  <div>
    <el-table
      class="tableClass"
      empty="--"
      v-loading="loading"
      :height="height"
      stripe
      border
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="isSel" type="selection" width="55" align="center" fixed="left" />
      <el-table-column v-if="index" label="序号" type="index" width="70" fixed="left" align="center" />
      <template v-for="(columnItem, index) in tableColumn" :key="`table${index}`">
        <!--  `${(80 / tableColumn.length) * (10 + columnItem.label)}` -->
        <el-table-column
          :fixed="columnItem.label == '操作' ? 'right' : false"
          :label="columnItem.label"
          :prop="columnItem.prop"
          :width="columnItem.width"
          :show-overflow-tooltip="columnItem.showText || !columnItem.width"
        >
          <template #default="{ row }">
            <slot
              name="columnCell"
              :record="row"
              :column="{
                prop: columnItem.prop,
                label: columnItem.label,
                width: columnItem.width
              }"
              >{{ getData(row, columnItem.prop, columnItem.label) }}</slot
            >
          </template>
        </el-table-column>
      </template>
    </el-table>
    <div v-if="isPage" class="pagination-container" :class="{ hidden: hidden }" id="paginationId">
      <el-pagination
        :background="background"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :layout="layout"
        :page-sizes="pageSizes"
        :pager-count="pagerCount"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<style scoped lang="scss">
.pagination-container {
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #fff;
}
.fixed {
  position: absolute;
  bottom: 0px;
  height: 2rem;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.pagination-container.hidden {
  display: none;
}
#paginationId ::v-deep .el-input__inner {
  width: 100px !important;
}
#paginationId ::v-deep .el-input {
  width: 100px !important;
}
#paginationId ::v-deep .el-select--default {
  width: 100px !important;
}
</style>
